import 'dart:math';
import 'dart:ui';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:get/get.dart';
import 'package:yi_shop/model/buyers.dart';
import 'package:yi_shop/route/index.dart';
import 'package:yi_shop/ui/draw_under_line.dart';
import 'package:yi_shop/utils/colors.dart';
import 'package:yi_shop/utils/styles.dart';
import 'package:yi_shop/utils/svg.dart';
import 'package:yi_shop/utils/tools.dart';

class CommunityTopicController extends GetxController {
  RxList<BuyersShowModel> pageList = RxList([]);

  late ScrollController scrollController;

  RxBool isLoading = false.obs;

  RxBool hasNext = true.obs;

  RxInt total = 35.obs;

  RxDouble opacity = 0.0.obs;

  double maxHeight = 103.0;

  @override
  void onInit() {
    initData();
    scrollController = ScrollController()
      ..addListener(() {
        final double t =
            clampDouble((scrollController.offset - kToolbarHeight) / maxHeight, 0.0, 1.0);
        opacity.value = t;
        if (isLoading.isFalse &&
            scrollController.position.pixels >= scrollController.position.maxScrollExtent) {
          isLoading.value = true;
          loadMoreData();
        }
      });
    super.onInit();
  }

  @override
  void onClose() {
    scrollController.dispose();
    super.onClose();
  }

  void loadMoreData() {
    Future<void>.delayed(const Duration(seconds: 3), () {
      if (total.value > pageList.length) {
        hasNext.value = true;
        isLoading.value = false;
        initData();
        return;
      }
      hasNext.value = false;
      isLoading.value = false;
    });
  }

  void initData() {
    final r = Random.secure();
    for (var i = 0; i < 10; i++) {
      pageList.add(BuyersShowModel(
          title: '#买家秀#',
          remark: '灰色沙发 蓝白地毯 毫无违和感',
          nickname: '青山美馆',
          imgUrls: [
            'https://gw.alicdn.com/tfs/TB15DvHUoz1gK0jSZLeXXb9kVXa-513-750.png_q90.jpg_.webp',
            'https://gw.alicdn.com/imgextra/i3/6000000005644/O1CN010O3Ad21rZ0JLlHk4R_!!6000000005644-0-lubanimage.jpg_q90.jpg_.webp',
            'https://gw.alicdn.com/imgextra/i3/6000000000724/O1CN01cBv6td1HDdeNDmvYJ_!!6000000000724-0-lubanimage.jpg_q90.jpg_.webp',
            'https://gw.alicdn.com/tfs/TB1mej8gdTfau8jSZFwXXX1mVXa-513-750.png_q90.jpg_.webp',
            'https://gw.alicdn.com/bao/uploaded/i2/681689952/O1CN01NQcFrM2NO4ZvGHFku_!!0-item_pic.jpg_320x320q90.jpg_.webp',
            'https://gw.alicdn.com/bao/uploaded/i1/2902239368/O1CN01X4bDXP2J4bGbEb4Ur_!!0-item_pic.jpg_320x320q90.jpg_.webp',
            'https://gw.alicdn.com/bao/uploaded/i4/1799996758/O1CN01kkJG9k1znDON5LsGx_!!0-item_pic.jpg_320x320q90.jpg_.webp'
          ],
          leaveMessage: r.nextInt(100),
          like: r.nextInt(100)));
    }
  }
}

class CommunityTopicPage extends GetView<CommunityTopicController> {
  const CommunityTopicPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        controller: controller.scrollController,
        slivers: [
          SliverAppBar(
            pinned: true,
            leading: ToolsUtils.builderLeading(),
            actions: [
              PopupMenuButton<int>(
                itemBuilder: (BuildContext context) {
                  return [
                    PopupMenuItem<int>(
                      height: 50,
                      padding: EdgeInsets.zero,
                      value: 0,
                      child: SizedBox(
                        height: 50,
                        width: 166,
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: [
                            Container(
                              width: 66,
                              height: 50,
                              alignment: Alignment.center,
                              child: SvgUtils.assetName('u11057', width: 20, height: 20),
                            ),
                            Expanded(
                                child: DrawUnderLine(
                              color: ColorsUtils.parseColorFromHexString(ColorsUtils.colorF2f2),
                              child: Container(
                                padding: const EdgeInsets.only(left: 10, right: 10),
                                alignment: Alignment.centerLeft,
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: [
                                    Text(
                                      '消息',
                                      style:
                                          StylesUtils.customTextStyle(color: ColorsUtils.color3333),
                                    ),
                                    Badge(
                                      smallSize: 20,
                                      backgroundColor: ColorsUtils.parseColorFromHexString(
                                          ColorsUtils.colorF048),
                                      textStyle: StylesUtils.customTextStyle(
                                          fontSize: StylesUtils.fontSize10),
                                      alignment: Alignment.center,
                                      label: const Text('6'),
                                    )
                                  ],
                                ),
                              ),
                            ))
                          ],
                        ),
                      ),
                    ),
                    PopupMenuItem<int>(
                        height: 50,
                        padding: EdgeInsets.zero,
                        value: 1,
                        child: SizedBox(
                          height: 50,
                          width: 166,
                          child: Row(
                            children: [
                              Container(
                                width: 66,
                                height: 50,
                                alignment: Alignment.center,
                                child: SvgUtils.assetName('u11070', width: 20, height: 20),
                              ),
                              Expanded(
                                  child: DrawUnderLine(
                                color: ColorsUtils.parseColorFromHexString(ColorsUtils.colorF2f2),
                                child: Container(
                                  padding: const EdgeInsets.only(left: 10),
                                  alignment: Alignment.centerLeft,
                                  child: Text(
                                    '首页',
                                    style:
                                        StylesUtils.customTextStyle(color: ColorsUtils.color3333),
                                  ),
                                ),
                              ))
                            ],
                          ),
                        )),
                    PopupMenuItem<int>(
                        height: 50,
                        padding: EdgeInsets.zero,
                        value: 2,
                        child: SizedBox(
                          height: 50,
                          width: 166,
                          child: Row(
                            children: [
                              Container(
                                width: 66,
                                height: 50,
                                alignment: Alignment.center,
                                child: SvgUtils.assetName('u11065', width: 20, height: 20),
                              ),
                              Expanded(
                                  child: DrawUnderLine(
                                color: ColorsUtils.parseColorFromHexString(ColorsUtils.colorF2f2),
                                child: Container(
                                  padding: const EdgeInsets.only(left: 10),
                                  alignment: Alignment.centerLeft,
                                  child: Text(
                                    '意见反馈',
                                    style:
                                        StylesUtils.customTextStyle(color: ColorsUtils.color3333),
                                  ),
                                ),
                              ))
                            ],
                          ),
                        )),
                    PopupMenuItem<int>(
                        height: 50,
                        padding: EdgeInsets.zero,
                        value: 3,
                        child: SizedBox(
                          height: 50,
                          width: 166,
                          child: Row(
                            children: [
                              Container(
                                width: 66,
                                height: 50,
                                alignment: Alignment.center,
                                child: SvgUtils.assetName('u11073', width: 20, height: 20),
                              ),
                              Expanded(
                                  child: DrawUnderLine(
                                color: ColorsUtils.parseColorFromHexString(ColorsUtils.colorF2f2),
                                child: Container(
                                  padding: const EdgeInsets.only(left: 10),
                                  alignment: Alignment.centerLeft,
                                  child: Text(
                                    '分享',
                                    style:
                                        StylesUtils.customTextStyle(color: ColorsUtils.color3333),
                                  ),
                                ),
                              ))
                            ],
                          ),
                        ))
                  ];
                },
                icon: const Icon(
                  Icons.more_vert,
                  size: 30,
                  weight: 700,
                  color: Colors.white,
                ),
                iconColor: Colors.white,
                iconSize: 30,
                elevation: 1,
                shadowColor: ColorsUtils.rgba(0, 0, 0, 0.35),
                shape:
                    Border.all(color: ColorsUtils.parseColorFromHexString(ColorsUtils.colorF2f2)),
                splashRadius: 5,
                surfaceTintColor: Colors.white,
                padding: EdgeInsets.zero,
                constraints: const BoxConstraints.expand(width: 166, height: 200),
                offset: const Offset(0, kToolbarHeight),
                onSelected: (int value) {
                  Get.log('selected = $value');
                },
              )
            ],
            expandedHeight: controller.maxHeight + kToolbarHeight,
            flexibleSpace: FlexibleSpaceBar(
              background: Column(
                children: [
                  Container(
                    height: kToolbarHeight + Get.mediaQuery.padding.top,
                  ),
                  Expanded(
                      child: Container(
                    color: Colors.white,
                    padding: const EdgeInsets.only(left: 20, top: 20),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Container(
                          constraints: const BoxConstraints.expand(width: 50, height: 50),
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                              color: ColorsUtils.parseColorFromHexString(ColorsUtils.colorF048),
                              borderRadius: BorderRadius.circular(5.r)),
                          child: Text(
                            '#',
                            style: StylesUtils.customTextStyle(fontSize: StylesUtils.fontSize36),
                          ),
                        ),
                        Expanded(
                            child: Container(
                          padding: EdgeInsets.only(left: 10.w),
                          child: Column(
                            children: [
                              Container(
                                margin: EdgeInsets.only(top: 5.w),
                                alignment: Alignment.centerLeft,
                                child: Text(
                                  '#买家秀#',
                                  style: StylesUtils.customTextStyle(
                                      color: ColorsUtils.color3333,
                                      fontSize: StylesUtils.fontSize16),
                                ),
                              ),
                              Container(
                                margin: EdgeInsets.only(top: 8.w),
                                alignment: Alignment.centerLeft,
                                child: Text(
                                  '阅读数：1567',
                                  style: StylesUtils.customTextStyle(color: ColorsUtils.color9999),
                                ),
                              )
                            ],
                          ),
                        ))
                      ],
                    ),
                  ))
                ],
              ),
              title: Obx(() => Text(
                    '#买家秀#',
                    style: StylesUtils.textStyle(
                        color: ColorsUtils.rgba(255, 255, 255, controller.opacity.value),
                        fontWeight: FontWeight.w700,
                        fontSize: StylesUtils.fontSize18),
                  )),
              centerTitle: false,
              collapseMode: CollapseMode.parallax,
            ),
          ),
          Obx(() => SliverList.list(
              children: controller.pageList
                  .map((row) => InkWell(
                        onTap: () {
                          Get.toNamed(RoutePath.communityTopicInfo);
                        },
                        child: Container(
                          margin: const EdgeInsets.only(top: 20),
                          color: Colors.white,
                          padding: const EdgeInsets.symmetric(vertical: 15, horizontal: 15),
                          child: Column(
                            children: [
                              Container(
                                alignment: Alignment.centerLeft,
                                child: Text(
                                  row.title,
                                  style: StylesUtils.customTextStyle(
                                    color: ColorsUtils.color0000,
                                  ),
                                ),
                              ),
                              Container(
                                alignment: Alignment.centerLeft,
                                padding: const EdgeInsets.symmetric(vertical: 15),
                                child: Text(
                                  row.remark,
                                  style: StylesUtils.customTextStyle(color: ColorsUtils.color6666),
                                ),
                              ),
                              StaggeredGrid.count(
                                crossAxisCount: 3,
                                crossAxisSpacing: 10,
                                mainAxisSpacing: 15,
                                children: row.imgUrls
                                    .map((e) => ClipRRect(
                                          borderRadius: BorderRadius.circular(5.r),
                                          child: CachedNetworkImage(
                                            imageUrl: e,
                                            width: 100,
                                            height: 100,
                                            fit: BoxFit.fill,
                                          ),
                                        ))
                                    .toList(),
                              ),
                              Container(
                                padding: const EdgeInsets.only(top: 15),
                                alignment: Alignment.centerLeft,
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  children: [
                                    Text(
                                      row.nickname,
                                      style: StylesUtils.customTextStyle(
                                          color: ColorsUtils.color6666,
                                          fontSize: StylesUtils.fontSize12),
                                    ),
                                    Wrap(
                                      spacing: 15,
                                      crossAxisAlignment: WrapCrossAlignment.center,
                                      alignment: WrapAlignment.end,
                                      children: [
                                        Text.rich(TextSpan(children: [
                                          WidgetSpan(
                                              child: SvgUtils.assetName('u10895',
                                                  width: 17, height: 15),
                                              alignment: PlaceholderAlignment.middle),
                                          TextSpan(
                                              text: ' ${row.leaveMessage}',
                                              style: StylesUtils.customTextStyle(
                                                  color: ColorsUtils.color9999,
                                                  fontSize: StylesUtils.fontSize13))
                                        ])),
                                        Text.rich(TextSpan(children: [
                                          WidgetSpan(
                                              child: SvgUtils.assetName('u10893',
                                                  width: 17, height: 15),
                                              alignment: PlaceholderAlignment.middle),
                                          TextSpan(
                                              text: ' ${row.like}',
                                              style: StylesUtils.customTextStyle(
                                                  color: ColorsUtils.color9999,
                                                  fontSize: StylesUtils.fontSize13))
                                        ]))
                                      ],
                                    )
                                  ],
                                ),
                              )
                            ],
                          ),
                        ),
                      ))
                  .toList())),
          Obx(() {
            if (controller.hasNext.isFalse) {
              return noBottom();
            }
            return renderBottom();
          })
        ],
      ),
    );
  }

  SliverToBoxAdapter noBottom() {
    return SliverToBoxAdapter(
      child: Container(
        padding: const EdgeInsets.symmetric(vertical: 15),
        alignment: Alignment.center,
        child: const Text(
          '已经到底',
          style: TextStyle(
            fontSize: 15,
            color: Color(0xFF333333),
          ),
        ),
      ),
    );
  }

  SliverToBoxAdapter renderBottom() {
    if (controller.isLoading.isTrue) {
      return SliverToBoxAdapter(
          child: Container(
        padding: const EdgeInsets.symmetric(vertical: 15),
        child: const Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              '努力加载中...',
              style: TextStyle(
                fontSize: 15,
                color: Color(0xFF333333),
              ),
            ),
            Padding(padding: EdgeInsets.only(left: 10)),
            SizedBox(
              width: 20,
              height: 20,
              child: CircularProgressIndicator(strokeWidth: 3),
            ),
          ],
        ),
      ));
    }
    return SliverToBoxAdapter(
        child: Container(
      padding: const EdgeInsets.symmetric(vertical: 15),
      alignment: Alignment.center,
      child: const Text(
        '上拉加载更多',
        style: TextStyle(
          fontSize: 15,
          color: Color(0xFF333333),
        ),
      ),
    ));
  }
}
